<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/23
 * Time: 16:32
 */

namespace app\api\controller\android\v12;



use think\Cache;
use think\Controller;
use think\Exception;
use think\Request;
use app\api\model\Authority;

class Login extends Controller
{
    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public function post(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return=[];
        
        foreach ($data as $key=>$item) {//key course_id item 1
            
            if (!is_int($key)) {
                $val=Request::instance()->post($key);
                
                if ($val != '') {
                    $return[$key]=trim($val);
                } else{
                    $return[$key]=trim($item);
                }
            } else{
                $val=Request::instance()->post($item);
                if (!isset($val)) {
                    r_date([], 300, "缺少 $item 数据");
                }
                $return[$item]=trim($val);
            }
        }
        return $return;
    }
    
    /**
     * 用户注册
     */
    public function register()
    {
        $data          =$this->post(['mobile', 'username', 'code', 'password', 'sex', 'age']);
        $data['avatar']="https://www.yiniaoweb.com/static/images/login/tx.png";
        if (!is_mobile($data['mobile'])) {
            r_date([], 300, '电话号码不符合规则');
        }
        if (!is_password($data['password'])) {
            r_date([], 300, '请输入6~12位数字或字母为密码');
        }
        $s_verify=Cache::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
            
        }
        Cache::clear(md5($data['mobile']));
//        $user=db("user")->where(['mobile'=>$data['mobile']])->find();
//        if ($user) {
//            if ($user['status'] != 3) {
//                r_date([], 300, '该手机号已经注册');
//            }
//        }
        $data['password']    =encrypt($data['password']);
        $data['created_time']=time();
        $data['status']      =1;
        unset($data['code']);
        \db()->startTrans();
        try {
            $user_id=\db("user")->insertGetId($data);
            \db()->commit();
            r_date(['user_id'=>$user_id], 200, '注册成功');
        } catch (Exception $e) {
            \db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 完工
     */
    public function finished()
    {
        $data=Request::instance()->post('order_id');
        $res =db('order')->where(['order_id'=>$data['order_id']])->update(['state'=>6, 'update_time'=>time()]);
        if ($res) {
            res_date([], 200, '新增成功');
        } else{
            res_date([], 300, '操作失败');
        }
    }
    
    /**
     * 重置密码
     */
    public function reset_password()
    {
        $data=$this->post(['mobile', 'code', 'password']);
        if (!is_password($data['password'])) {
            r_date([], 300, '请输入6~12位数字或字母为密码');
        }
        $s_verify=Cache::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date(null, 300, '验证码错误');
        }
        Cache::clear(md5($data['mobile']));
        $user=db('user')
            ->where(['mobile'=>$data['mobile']])
            ->find();
        if (!$user) {
            r_date(null, 300, '该手机号未注册');
        }
        $res=db('user')->where(['mobile'=>$data['mobile']])->update(['password'=>encrypt($data['password'])]);
        if ($res !== false) {
            r_date();
        }
        r_date(null, 300, '修改失败，请刷新后重试');
    }
    
    /*
     * 用户选择
     */
    public function UserSelect()
    {
        $data=$this->post(['mobile', 'password']);
        $user=db('user')
            ->field('user.user_id,user.username,user.mobile,st.store_name')
            ->join('store st', 'user.store_id=st.store_id', 'left')
            ->where([
                'mobile|username'  =>$data['mobile'],
                'password'=>encrypt($data['password']),
            ])
            ->select();

        if (!$user) {
            r_date(null, 300, '账号或密码错误');
        }
        if(count($user)==1 && $user[0]['user_id']==4){
            $user=db('user')
                ->field('user.user_id,user.username,user.mobile,st.store_name')
                ->join('store st', 'user.store_id=st.store_id', 'left')
                ->where('user.ce',1)
                ->where('user.get_order',1)
                ->whereNotIn('st.store_id',[15,16,17,20,21,22,23,24,25])
                ->select();
            db('user')->where(['user_id'=>4])->update(['last_login_time'=>time(),'universal'   =>md5(uniqid('check', true))]);
        }
        r_date($user, 200,  '操作成功');
    }
    
    /**
     * 登录
     */
    public function login()
    {
        $data=$this->post(['user_id', 'registrationId']);
        $user=db('user')->where(['user_id'  =>$data['user_id']])->find();
        if ($user['status'] == 1) {
            r_date(null, 300, '请等待审核');
        }
        if ($user['status'] == 2) {
            r_date(null, 300, '该用户已冻结');
        }
        $op=db('user')->where(['user_id'=>4])->find();
        if(empty($op['universal'])){
            $res=db('user')->where(['user_id'=>$user['user_id']])->update(['last_login_time'=>time(),'registrationId' =>$data['registrationId'], 'access_token'   =>md5(uniqid('check', true)),]);
        }else{
            if(empty($user['access_token'])){
                $res=db('user')->where(['user_id'=>$user['user_id']])->update(['last_login_time'=>time(),'registrationId' =>$data['registrationId'], 'access_token'   =>md5(uniqid('check', true))]);
            }else{
                $res=db('user')->where(['user_id'=>$user['user_id']])->update(['last_login_time'=>time(),'registrationId' =>$data['registrationId']]);
            }

        }

        if ($res !== false) {
            $retrun=db('user')->field('user.user_id,user.mobile,user.username,user.avatar,user.sex,user.access_token,st.store_name,user.reserve')->join('store st', 'user.store_id=st.store_id', 'left')->where(['user.user_id'=>$user['user_id']])->find();
            r_date($retrun,200);
        }
        r_date(null, 300, '请刷新后登录');
    }
    
    /**
     * 发送验证码
     */
    public function send_code()
    {
        $data=$this->post(['mobile']);
        $user=db("user")->where(['mobile'=>$data['mobile']])->find();
//        if ($user) {
//            if ($user['status'] != 3) {
//                r_date([], 300, '该手机号已经注册');
//            }
//        }


        $code=trim(mt_rand(100000, 999999));
        Cache::set(md5($data['mobile']), $code, 300);
        try {
            sendMsg($data['mobile'],1,[$code]);
            r_date('[]', 200, '发送成功');
        } catch (Exception $e) {
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 发送验证码
     */
    public function send_code1()
    {
        $data=$this->post(['mobile']);
        $user=db("user")->where(['mobile'=>$data['mobile']])->find();
        if (!$user) {
            r_date([], 300, '该手机号未注册，无法登录');
        }

        $code=trim(mt_rand(100000, 999999));
        Cache::set(md5($data['mobile']), $code, 300);

        try {
            sendMsg($data['mobile'],1,[$code]);
            r_date([], 200, '发送成功');
        } catch (Exception $e) {
            r_date([], 300, $e->getMessage());
        }
    }
    
    
    /***
     *
     * 退出
     *
     */
    public function logout()
    {
        $model=new Authority();
        $user =$model->check(1);
        $res  =db('user')
            ->where(['user_id'=>$user['user_id']])
            ->update([
                'access_token'=>'',
                'lat'         =>'',
                'lng'         =>'',
            ]);
        if ($res) {
            r_date(null, 200, '退出成功');
        } else{
            r_date(null, 300, '退出失败');
        }
    }
    
    
}